<template>
  <div>
    <el-container style="background: #f5f7f9;">
      <el-header style="background: #fff;padding: 12px 12px;height:auto;">
        <div>
          <el-form :model="queryData" :inline="true" size="small">
            <el-form-item label="状态">
              <el-radio-group v-model="queryData.type" size="small" @change="queryOrder()">
                <el-radio-button label="all">所有订单</el-radio-button>
                <el-radio-button label="cancelled">已删除</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="!isOrgOwner" label="客户">
              <el-select v-model="queryData.orgOwner" clearable filterable>
                <el-option v-for="(d, i) in customerOptions" :key="i" :label="d.orgOwnerName" :value="d.orgOwner" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态">
              <el-select v-model="queryData.status" clearable filterable>
                <el-option v-for="(d, i) in statusOptions" :key="i" :label="d.name" :value="d.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="queryData.orderId" :rows="1" style="width: 280px;" type="textarea" placeholder="多个单号用回车分割" />
            </el-form-item>
            <el-form-item label="客户订单号">
              <el-input v-model="queryData.customerRef" :rows="1" style="width: 280px;" type="textarea" placeholder="多个单号用回车分割" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchData()">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main style="margin-top: 15px; background: #fff;padding: 12px 16px 0 16px;height: 100%;">
        <div style="height: 100%;display: flex;">
          <template v-if="isOrgOwner" v-has="70204">
            <el-button size="small" @click="importOrderDialogShow = true">私人地址模板导入</el-button>
            <el-button size="small" @click="importOrderDialogShow2 = true">fba地址模板导入</el-button>
            <el-button size="small" @click="importOrderDialogShow3 = true">fba号补录</el-button>
            <el-button size="small" @click="download">导出近一月订单</el-button>
          </template>
          <template v-else>
            <el-button size="small" @click="deleteOrders">删除</el-button>
            <el-button size="small" @click="download">导出近一月订单</el-button>
          </template>
        </div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          stripe
          tooltip-effect="dark"
          :max-height="tableHeight"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column fixed prop="orderNumber" label="订单号" />
          <el-table-column prop="customerRef" label="客户订单号" />
          <el-table-column prop="orgOwnerName" label="客户" />
          <el-table-column prop="channelName" label="产品" />
          <el-table-column label="仓码/邮编">
            <template slot-scope="scope">
              {{ scope.row.consigneeAddress.fbaCode ? scope.row.consigneeAddress.fbaCode : scope.row.consigneeAddress.zipCode }}
            </template>
          </el-table-column>
          <el-table-column prop="totalCarton" width="55" label="箱数" />
          <el-table-column prop="totalWeight" label="打单重量" />
          <el-table-column prop="totalVolume" label="打单总体积(CBM)" />
          <el-table-column prop="createAt" label="创建时间" />
          <el-table-column prop="status" label="订单状态" />
          <el-table-column prop="totalChargePrepaid" label="预付费用" />
          <el-table-column prop="totalCharge" label="实付费用" />
          <el-table-column prop="totalChargeDiff" label="差额" />
          <el-table-column v-if="!isOrgOwner" prop="totalCost" label="实际成本" />
          <el-table-column v-if="!isOrgOwner" prop="profit" label="利润" />
          <el-table-column label="打印状态">
            <template slot-scope="scope">
              {{ scope.row.labelDownloaded ? "已打印":"未打印" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button v-has="70201" size="small" shape="circle" type="text" @click="showDetail(scope.row)">明细</el-button>
              <!-- <el-button v-has="70202" v-if="!isOrgOwner && scope.row.status!='取消'" size="small" shape="circle" type="text" @click="handleDelete(scope.row)">取消</el-button> -->
              <el-button v-if="queryData.type !== 'cancelled'" v-has="70203" size="small" shape="circle" type="text" @click="downloadLabel(scope.row)">下载面单</el-button>
            <!-- <el-button v-if="isAdmin && scope.row.status == 'cancelled'" size="small" shape="circle" type="text" @click="restore(scope.row)">恢复订单</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer style="padding:0;background: #fff;">
        <div style="text-align: right; padding-top: 10px;">
          <!-- 分页 -->
          <el-pagination
            background
            :current-page="queryData.currentPage"
            :page-sizes="[50, 100, 200, 300, 400]"
            :page-size="queryData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="float: right;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-footer>
    </el-container>
    <el-dialog title="费用明细" class="common-select__dialog" :visible.sync="dialogCheckVisible1" width="700px">
      <el-table ref="table" :data="orderCostData" border style="width: 100%;" max-height="800" class="order-charge__table">
        <el-table-column prop="serviceType" label="费用类型" />
        <el-table-column prop="salesAmount" label="金额" />
      </el-table>
    </el-dialog>
    <el-dialog title="批量上传私人地址订单" :visible.sync="importOrderDialogShow" width="30%">
      <el-upload :action="importOrderUrl" :on-success="importOrderCallBack" name="file" :limit="1" :file-list="importOrderFileList" accept=".xlsx" :with-credentials="true" :show-file-list="false" style="display: inline-block;">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <a href="/template/truck_order_list.xlsx" download="卡派私人地址模板.xlsx" style="margin-left:50px;display: inline-block; vertical-align: top;">
        <el-button size="small" type="text">下载模板</el-button>
      </a>
    </el-dialog>

    <el-dialog title="批量上传FBA订单" :visible.sync="importOrderDialogShow2" width="30%">
      <el-upload :action="importFbaOrderUrl" :on-success="importOrderCallBack" name="file" :limit="1" :file-list="importOrderFileList" accept=".xlsx" :with-credentials="true" :show-file-list="false" style="display: inline-block;">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <a href="/template/truck_order_list_fba.xlsx" download="卡派FBA地址模板.xlsx" style="margin-left:50px;display: inline-block; vertical-align: top;">
        <el-button size="small" type="text">下载模板</el-button>
      </a>
    </el-dialog>
    <el-dialog title="批量补录FBA号(注意:每次补录都是覆盖之前的数据)" :visible.sync="importOrderDialogShow3" width="30%">
      <el-upload :action="importFbaNumberUrl" :on-success="importOrderCallBack" name="file" :limit="1" :file-list="importOrderFileList" accept=".xlsx" :with-credentials="true" :show-file-list="false" style="display: inline-block;">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <a href="/template/truck_fba_number.xlsx" download="FBA号补录模板.xlsx" style="margin-left:50px;display: inline-block; vertical-align: top;">
        <el-button size="small" type="text">下载模板</el-button>
      </a>
    </el-dialog>

    <el-dialog :visible.sync="detailDialogVisible" width="70%" center :close-on-click-modal="false">
      <el-collapse v-model="detailExpandItems" @change="collapseChange">
        <el-collapse-item name="1" title="基础信息">
          <el-row>
            <el-col :span="6">订单号:&nbsp;&nbsp;{{ detail.orderNumber }}</el-col>
            <el-col :span="6">客户订单号:&nbsp;&nbsp;{{ detail.customerRef }}</el-col>
            <el-col :span="6">客户:&nbsp;&nbsp;{{ detail.orgOwnerName }}</el-col>
            <el-col :span="6">产品:&nbsp;&nbsp;{{ detail.channelName }}</el-col>
          </el-row>
          <br>
          <el-row>
            <el-col :span="6">总体积(立方米):&nbsp;&nbsp;{{ detail.totalVolume }}</el-col>
            <el-col :span="6">总重量(KG):&nbsp;&nbsp;{{ detail.totalWeight }}</el-col>
            <el-col :span="6">下单时间:&nbsp;&nbsp;{{ detail.createAt }}</el-col>
            <el-col :span="6">亚马逊仓码:&nbsp;&nbsp;{{ detail.consigneeAddress.fbaCode }}</el-col>
          </el-row>
          <br>
          <el-row>
            <el-col :span="6">收件人:&nbsp;&nbsp;{{ detail.consigneeAddress.contacter }}</el-col>
            <el-col :span="6">电话:&nbsp;&nbsp;{{ detail.consigneeAddress.phone }}</el-col>
            <el-col :span="6">国家:&nbsp;&nbsp;{{ detail.consigneeAddress.countryCode }}</el-col>
            <el-col :span="6">州/省:&nbsp;&nbsp;{{ detail.consigneeAddress.state }}</el-col>
          </el-row>
          <br>
          <el-row>
            <el-col :span="6">城市:&nbsp;&nbsp;{{ detail.consigneeAddress.city }}</el-col>
            <el-col :span="6">公司名:&nbsp;&nbsp;{{ detail.consigneeAddress.company }}</el-col>
            <el-col :span="6">邮编:&nbsp;&nbsp;{{ detail.consigneeAddress.zipCode }}</el-col>
          </el-row>
          <br>
          <el-row>
            <el-col :span="24">地址1:&nbsp;&nbsp;{{ detail.consigneeAddress.address }}</el-col>
          </el-row>
          <br>
          <el-row>
            <el-col :span="24">地址2:&nbsp;&nbsp;{{ detail.consigneeAddress.address2 }}</el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item name="3" title="订单费用">
          <el-table border :data="detail.txs">
            <el-table-column prop="chargeType" label="费用科目" />
            <el-table-column prop="amount" label="金额" />
            <el-table-column prop="currency" label="币种" />
          </el-table>
        </el-collapse-item>
        <el-collapse-item name="4" title="FBA号">
          <el-table border :data="detail.refs">
            <el-table-column prop="fbaId" label="FBA号" />
            <el-table-column prop="referenceId" label="Reference ID" />
            <el-table-column prop="qty" label="件数" />
          </el-table>
        </el-collapse-item>
        <el-collapse-item name="5" title="轨迹">
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in detail.tracking"
              :key="index"
              color="#0bbd87"
            >
              <div>
                <p style="line-height:1">{{ item.event }}</p>
                <p v-if="item.eventAt" style="line-height:1">{{ '实际时间:' + item.eventAt }} </p>
                <p v-if="item.eventAtExpecting" style="line-height:1">{{ '预计时间:' + item.eventAtExpecting }}</p>
                <p v-if="item.remark" style="line-height:1">{{ '备注:' + item.remark }}</p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-collapse-item>
      </el-collapse>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import request from '@/utils/request'
import config from '@/settings'
import { copyProperty } from '@/utils/tools'
const BASE_URL = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
export default {
  components: {},
  data() {
    return {
      detailOrderId: '',
      importOrderUrl: BASE_URL + '/truck/import-order',
      importOrderFileList: [],
      importFbaOrderUrl: BASE_URL + '/truck/import-fba-order',
      importFbaNumberUrl: BASE_URL + '/truck/import-fba-number',
      importOrderDialogShow: false,
      importOrderDialogShow2: false,
      importOrderDialogShow3: false,
      batch_upload_mask: false,
      formLabelWidth: '120px',
      downloadLabelCtx: {
        date: '',
        orderIds: ''
      },
      detailDialogVisible: false,
      conditions: {
        export: 0,
        status: '',
        product: '',
        number: '',
        startDate: '',
        endDate: '',
        orgId: '',
        currentPage: 1,
        pageSize: 100,
        trackingNumbers: []
      },
      queryData: {
        pageSize: 50,
        currentPage: 0,
        orgOwner: '',
        orderId: '',
        customerRef: '',
        channelId: '',
        status: '',
        type: 'all'
      },
      detailDefault: {
        orderNumber: '',
        channelName: '',
        customerRef: '',
        consigneeAddress: {
          contacter: '',
          phone: '',
          countryCode: '',
          state: '',
          city: '',
          address: '',
          address2: '',
          company: '',
          zipCode: '',
          fbaCode: '',
          deliverySignature: 'false'
        },
        cartons: [],
        createAt: '',
        orgOwnerName: '',
        totalCarton: 0,
        totalVolume: '',
        totalWeight: '',
        txs: [],
        packingListTableBody: [],
        trackingNumbers: []
      },
      detail: {
        orderNumber: '',
        channelName: '',
        customerRef: '',
        consigneeAddress: {
          contacter: '',
          phone: '',
          countryCode: '',
          state: '',
          city: '',
          address: '',
          address2: '',
          company: '',
          zipCode: '',
          fbaCode: '',
          deliverySignature: 'false'
        },
        cartons: [],
        createAt: '',
        orgOwnerName: '',
        totalCarton: 0,
        totalVolume: '',
        totalWeight: '',
        txs: [],
        packingListTableBody: [],
        trackingNumbers: [],
        refs: [],
        tracking: []
      },
      detailExpandItemsDefault: ['1', '2'],
      detailExpandItems: ['1', '2'],
      numberTextArea: '',
      trackingNumbers: '',
      orgs: [],
      tableData: [],
      multipleSelection: [],
      customerList: [],
      currentPage: 1, // 分页
      dialogFormVisible: false,
      dialogUpLoadVisible: false,
      dialogCheckVisible: false,
      dialogCheckVisible1: false,
      checkForm: {
        radio: '1',
        text: ''
      },
      total: 0,
      createOrderform: {
        product: '',
        customer: ''
      },
      createOrderformRules: {
        product: [{ required: true, message: '请选择产品', trigger: 'change' }],
        customer: [{ required: true, message: '请选择客户', trigger: 'change' }]
      },
      channelProduct: [],
      channelMap: {},
      statusMap: {},
      isAdmin: false,
      orderCostData: [],
      statusOptions: []
    }
  },
  computed: {
    tableHeight() {
      return document.documentElement.clientHeight - 330
    },
    ...mapState(//
      {
        paymentTerm: state => state.base.paymentTerm,
        customerOptions: state => state.base.customerOptions,
        profile: state => state.user,
        orderStatusOptions: state => state.base.orderStatusOptions
      }
    ),
    isOrgOwner() {
      return this.profile.orgOwner
    }
  },
  created() {
    this.queryOrder()
    this.loadStatusOption()
  },
  methods: {
    download() {
      const orderNumber = []
      this.multipleSelection.forEach(e => {
        orderNumber.push(e.orderNumber)
      })
      this.queryData.orderId = orderNumber.join('\n')
      request({
          url: 'truck/download',
          data: this.queryData,
          method: 'post'
        }).then(res => {
          this.queryData.orderId = ''
          if (res.success) {
            const link = document.createElement('a')
            const array = this.base64ToUint8Array(res.data)
            const blob = new Blob([array])
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', `卡派订单明细.xlsx`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        })
    },
    base64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4)
      const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
      const rawData = window.atob(base64)
      const outputArray = new Uint8Array(rawData.length)
      for (let i = 0; i < rawData.length; ++i) {
          outputArray[i] = rawData.charCodeAt(i)
      }
      return outputArray
    },
    cartonTableSpanMethod(row) {
      if (row.row.rowSpan > 0 && row.columnIndex <= 4) {
        return [row.row.rowSpan, 1]
      } else if (row.columnIndex > 4) {
        return [1, 1]
      } else if (row.columnIndex <= 4) {
        return [0, 1]
      }
    },
    importOrderCallBack(res) {
      if (res.success) {
        this.$message.success('成功')
        this.importOrderDialogShow = false
        this.importOrderDialogShow2 = false
        this.importOrderDialogShow3 = false
        this.importOrderFileList = []
        this.queryOrder()
      } else {
        this.importOrderFileList = []
        this.$message({
          message: res.message,
          type: 'error',
          duration: 0,
          showClose: true
        })
      }
    },
    doBatchDownloadLabel() {
      var _this = this
      if (_this.lm_system) {
        if (!_this.downloadLabelCtx.orderIds) {
          this.$notify.info({
            title: '提示',
            message: '请输入订单号'
          })
          return
        }
      } else {
        if (!_this.downloadLabelCtx.date) {
           this.$notify.info({
            title: '提示',
            message: '请选择日期'
        })
        return
        }
      }
    },
    exportCharge() {
    },
    searchData() {
      this.queryData.currentPage = 1
      this.queryOrder()
    },
    // 搜索
    queryOrder() {
      request({
        url: 'truck/query',
        data: this.queryData,
        method: 'post'
      }).then(res => {
        if (res.success) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    loadStatusOption() {
      request({
        url: 'truck/status-option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.statusOptions = res.data
        }
      })
    },
    getLabels() {
      const _this = this
      const orderIds = []
      if (_this.multipleSelection.length === 0) {
        _this.$message({
          type: '提示',
          message: '请选择订单'
        })
        return
      }
      _this.multipleSelection.forEach(a => {
        orderIds.push(a.id)
      })
      window.open()
    },
    deleteOrders() {
      const orderIds = []
      if (this.multipleSelection.length === 0) {
       this.$message.error('请选择订单')
        return
      }
      this.multipleSelection.forEach(a => {
        orderIds.push(a.orderId)
      })
      this.$confirm('是否取消订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: 'order/dels',
          data: { orderIds: orderIds },
          method: 'post'
        }).then(res => {
          if (res.success) {
            this.queryOrder()
          }
        })
      })
    },
    exportOrders() {
      const _this = this
      _this.conditions.number = []
      _this.numberTextArea.split(/\n+/gim).forEach((d, i) => {
        if (d && d !== '') {
          _this.conditions.number.push(d)
        }
      })

      let notStatus = []
      const s = _this.conditions.status
      if (s === '') {
        notStatus = ['cancelled', 'exception']
      } else if (s === 'cancelled') {
        notStatus = ['exception']
      }

      var submitForm = {
        status: _this.conditions.status,
        orgId: _this.conditions.orgId,
        productId: _this.conditions.product,
        orderId: _this.conditions.number,
        startDate: _this.conditions.startDate,
        endDate: _this.conditions.endDate,
        currentPage: _this.conditions.currentPage,
        pageSize: _this.conditions.pageSize,
        notStatus: notStatus,
        export: 1,
        orderIds: []
      }
      _this.multipleSelection.forEach(a => {
        submitForm.orderIds.push(a.id)
      })
    },
    // 查看
    showDetail(row) {
      this.detailOrderId = row.orderId
      this.detailExpandItems = []
      this.detailExpandItems = [...this.detailExpandItemsDefault]
      this.detailDialogVisible = true
      copyProperty(this.detail, this.detailDefault)
      copyProperty(this.detail, row)
      // copyProperty(this.detail.consigneeAddress, row.consigneeAddress)
      // this.detail.channelName = row.channelName + ''
      // this.detail.orgOwnerName = row.orgOwnerName
      // this.detail.orderNumber = row.orderNumber
      // this.detail.customerRef = row.customerRef
      this.drawerTitle = '明细'
    },
    flatCartionDetail(cartons) {
      const flats = []
      // sameSpecCartons
      cartons.forEach(c => {
        for (let i = 0; i < c.details.length; i++) {
         const flat = {
            'rowSpan': 0,
            'length': '',
            'width': '',
            'height': '',
            'weight': '',
            'skuNameEn': '',
            'skuNameCn': '',
            'qty': '',
            'skuWeight': '',
            'unitPrice': '',
            'currency': '',
            'sameSpecCartons': ''
          }
          if (i === 0) {
            flat.rowSpan = c.details.length
          }
          copyProperty(flat, c)
          copyProperty(flat, c.details[i])
          flats.push(flat)
        }
      })
      return flats
    },
    collapseChange(item) {
      item.forEach(ele => {
        switch (ele) {
          case '3':
            this.loadTxs(this.detailOrderId)
            break
          case '4':
            this.loadFbaRefs(this.detailOrderId)
            break
          case '5':
            this.loadTracking(this.detailOrderId)
            break
        }
      })
    },
    loadFbaRefs(orderId) {
      request({
        url: 'truck/fba-refs?orderId=' + orderId,
        method: 'get'
      }).then(res => {
        if (res.success) {
         this.detail.refs = res.data
        }
      })
    },
    loadTracking(orderId) {
      request({
        url: 'order/tracking?orderId=' + orderId,
        method: 'get'
      }).then(res => {
        if (res.success) {
         this.detail.tracking = res.data
        }
      })
    },
    loadTxs(orderId) {
      request({
        url: 'order/tx?orderId=' + orderId,
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.detail.txs = res.data
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否取消的订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
        url: 'truck/del?orderId=' + row.orderId,
        method: 'get'
      }).then(res => {
        if (res.success) {
         this.queryOrder()
        }
      })
      })
    },
    restore(index, row) {
      this.$confirm('是否恢复订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      })
    },
    downloadLabel(row) {
      request({
        url: '/d/lm-label-truck?orderId=' + row.orderId,
        method: 'get'
      }).then(res => {
        if (res.success) {
            window.open(res.data)
        }
      })
    },
    downloadCartonLabel(index, row) {
        window.open()
    },
    downloadSystemLabel(index, row) {
       const _this = this
      if (row.systemLabelUrl != null && row.systemLabelUrl != '') {
        window.open(row.systemLabelUrl)
      } else {
        _this.$message.info('还没有生成')
      }
    },
    // 多选按钮
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    // 分页
    handleSizeChange(val) {
      this.queryData.currentPage = 1
      this.queryData.pageSize = val
      this.queryOrder()
    },
    handleCurrentChange(val) {
      this.queryData.currentPage = val
      this.queryOrder()
    },
    showOrderCostDetail(row) {
      this.dialogCheckVisible1 = true
      this.orderCostData = []
      row.forEach((item, index) => {
        if (item.salesAmount > 0) {
          this.orderCostData.push(item)
        }
      })
    }
  }
}
</script>
